package com.caigou.comm.base.viewmodel

import android.text.TextUtils
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.caigou.comm.base.ext.Resource
import com.caigou.comm.base.repository.CommRepository
import com.caigou.comm.base.utils.Logger
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch
import javax.inject.Inject

/**
 * @author #Suyghur.
 * Created on 2022/01/06
 */
@HiltViewModel
class FollowViewModel @Inject constructor(private val repository: CommRepository) : ViewModel() {

    val followLiveData = MutableLiveData<Resource<String>>()

    fun setFollow(followUserId: String, masterUserId: String) {
        followLiveData.value = Resource.Loading()
        viewModelScope.launch {
            repository.setFollow(followUserId, masterUserId)
                .map {
                    if (it.code == 0) {
                        Resource.Success(it.msg)
                    } else {
                        Resource.DataError(it.code, it.msg)
                    }
                }
                .catch {
                    val message = if (TextUtils.isEmpty(it.message)) {
                        ""
                    } else {
                        it.message!!
                    }
                    Resource.DataError<String>(-1, message)
                    Logger.e("catch: ${it.message}")
                }
                .collectLatest {
                    followLiveData.value = it
                }
        }
    }
}